package com.zzyl.serve.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.serve.domain.NursingPlan;
import com.zzyl.serve.domain.NursingProjectPlan;
import com.zzyl.serve.dto.NursingPlanDto;
import com.zzyl.serve.mapper.NursingPlanMapper;
import com.zzyl.serve.service.INursingPlanService;
import com.zzyl.serve.service.INursingProjectPlanService;
import com.zzyl.serve.vo.NursingPlanVo;
import com.zzyl.serve.vo.NursingProjectPlanVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 护理计划Service业务层处理
 *
 * @author ruoyi
 * @date 2024-10-04
 */
@Service
public class NursingPlanServiceImpl extends ServiceImpl<NursingPlanMapper, NursingPlan> implements INursingPlanService {
    @Autowired
    private NursingPlanMapper nursingPlanMapper;
    @Autowired
    private INursingProjectPlanService nursingProjectPlanService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询护理计划列表
     *
     * @param nursingPlan 护理计划
     * @return 护理计划
     */
    @Override
    public List<NursingPlan> selectNursingPlanList(NursingPlan nursingPlan) {
        return nursingPlanMapper.selectNursingPlanList(nursingPlan);
    }

    /**
     * 批量删除护理计划
     *
     * @param ids 需要删除的护理计划主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteNursingPlanByIds(Long[] ids) {
        // 1.批量删除护理计划关联的护理项目
        // delete from nursing_project_plan where plan_id in (1,2,3)
        nursingProjectPlanService.remove(Wrappers.<NursingProjectPlan>lambdaQuery().in(NursingProjectPlan::getPlanId, ids));

        // 2.删除缓存
        deleteCache();

        // 3.删除护理计划基本信息
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除护理计划信息
     *
     * @param id 护理计划主键
     * @return 结果
     */
    @Override
    public int deleteNursingPlanById(Long id) {
        // 删除缓存
        deleteCache();
        return removeById(id) ? 1 : 0;
    }

    /**
     * 2- 新增护理计划（Day4 - 课堂2）
     *
     * @param nursingPlan 护理计划
     * @return 结果
     */
    @Override
    @Transactional
    public int insertNursingPlan(NursingPlanDto nursingPlanDto) {
        // 1.保存护理计划基本信息
        NursingPlan nursingPlan = BeanUtil.toBean(nursingPlanDto, NursingPlan.class);
        this.save(nursingPlan); // mybatisPlus的save()保存完数据后，会自动返回主键

        // 2.批量保存护理计划关联的护理项目
        List<NursingProjectPlan> projectPlans = nursingPlanDto.getProjectPlans();
        projectPlans.forEach(item -> item.setPlanId(nursingPlan.getId()));
        boolean result = nursingProjectPlanService.saveBatch(projectPlans);

        // 3、删除缓存
        deleteCache();

        // 4.返回结果
        return result ? 1 : 0;
    }

    /**
     * 3- 查询护理计划（Day4 - 课堂3）
     *
     * @param id 护理计划主键
     * @return 护理计划
     */
    @Override
    public NursingPlanVo selectNursingPlanById(Long id) {
        // 1.获取护理计划基本信息
        NursingPlan nursingPlan = getById(id);

        // 2.获取当前护理计划关联的护理项目列表
        List<NursingProjectPlan> list = this.nursingProjectPlanService.lambdaQuery()
                .eq(NursingProjectPlan::getPlanId, id)
                .list();

        List<NursingProjectPlanVo> projectList = list.stream().map(item -> {
            NursingProjectPlanVo nursingProjectPlanVo = BeanUtil.toBean(item, NursingProjectPlanVo.class);
            nursingProjectPlanVo.setProjectId(String.valueOf(item.getProjectId()));
            nursingProjectPlanVo.setExecuteCycle(String.valueOf(item.getExecuteCycle()));
            return nursingProjectPlanVo;
        }).collect(Collectors.toList());

        // 3.构建一个NursingPlanVo对象并返回
        NursingPlanVo nursingPlanVo =  BeanUtil.toBean(nursingPlan, NursingPlanVo.class);
        nursingPlanVo.setProjectPlans(projectList);

        return nursingPlanVo;
    }

    /**
     * 4- 修改护理计划（Day4 - 课堂4）
     *
     * @param nursingPlan 护理计划
     * @return 结果
     */
    @Override
    @Transactional
    public int updateNursingPlan(NursingPlanDto nursingPlanDto) {
        // 1.修改护理计划关联的护理项目列表
        List<NursingProjectPlan> projectPlans = nursingPlanDto.getProjectPlans();

        // 2.判断护理计划关联的护理项目是否为空
        if (projectPlans != null && !projectPlans.isEmpty()) {
            // 1.1 删除当前护理计划关联的所有护理项目
            nursingProjectPlanService.remove(Wrappers.<NursingProjectPlan>lambdaQuery().eq(NursingProjectPlan::getPlanId, nursingPlanDto.getId()));

            // 2.2 批量保存护理计划新关联的护理项目
            projectPlans.forEach(item -> item.setPlanId(nursingPlanDto.getId()));
            nursingProjectPlanService.saveBatch(projectPlans);
        }

        // 3.修改护理计划的基本信息
        NursingPlan nursingPlan = new NursingPlan();
        BeanUtils.copyProperties(nursingPlanDto, nursingPlan);

        // 4.删除缓存
        deleteCache();

        return updateById(nursingPlan) ? 1 : 0;
    }

    private void deleteCache() {
        redisTemplate.delete(CacheConstants.NURSING_PLAN_ALL_KEY);
    }

    /**
     * 查询所有护理计划
     *
     * @return 护理计划列表
     */
    @Override
    public List<NursingPlan> getAllNursingPlans() {
        // 1.先查询缓存，如果缓存中有直接返回
        List<NursingPlan> nursingPlans = (List<NursingPlan>) redisTemplate.opsForValue().get(CacheConstants.NURSING_PLAN_ALL_KEY);

        if (ObjectUtils.isNotEmpty(nursingPlans)) {
            return nursingPlans;
        }

        // 2.如果缓存中没有，再查询数据库，并将结果添加到缓存中
        nursingPlans = this.lambdaQuery().eq(NursingPlan::getStatus, 1).list();

        // 3.将结果添加到缓存
        redisTemplate.opsForValue().set(CacheConstants.NURSING_PLAN_ALL_KEY, nursingPlans);

        return nursingPlans;
    }
}
